package com.smart.village.big.screen.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.ContiguousSet;
import com.google.common.collect.Lists;
import com.smart.village.big.screen.domain.VideosCategory;
import com.smart.village.big.screen.domain.Videos;
import com.smart.village.big.screen.domain.VideosCategory;
import com.smart.village.big.screen.domain.VideosTags;
import com.smart.village.big.screen.mapper.VideosMapper;
import com.smart.village.big.screen.service.VideosService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.swing.text.View;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class VideosServiceImpl implements VideosService {
    @Autowired
    private VideosMapper videosMapper;

    @Override
    public List<JSONObject> getVideosByCategory(String category, String search,String phone, int environment ,int pageNum, int pageSize) {
        List<JSONObject> list = Lists.newArrayList();
        if(ObjectUtils.isEmpty(category)){
            List<String> treeList = Lists.newArrayList();
            List<HashMap<String, Object>> treeListByParentSerialNumber = videosMapper.getVideosCategoryChildIdList("");
            if (!ObjectUtils.isEmpty(treeListByParentSerialNumber)) {
                treeListByParentSerialNumber.forEach(nc -> {
                    treeList.add(nc.get("videoCategorySerialNumber").toString());
                });
            }
            treeList.forEach(ca -> {
                PageHelper.startPage(pageNum, pageSize);
                List<Videos> videosByCategory = videosMapper.getVideosByCategory(ca,search,environment);
                for (Videos nc : videosByCategory) {
                    if (nc.getCreateDatetime() != null) {
                        try {
                            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            if (( new Date().getTime() - dateFormat.parse(nc.getCreateDatetime()).getTime())/(24*60*60*1000) <= 3) {
                                nc.setIfNew("1");
                            }else{
                               nc.setIfNew("0");
                            }
                            if(StringUtils.isNotEmpty(phone)) {
                                JSONObject lastRecentViewRecord = videosMapper.getLastRecentViewRecord(nc.getVideoSerialNumber(), phone);
                                if (!ObjectUtils.isEmpty(lastRecentViewRecord)) {
                                    nc.setLastRecentViewRecord(lastRecentViewRecord);
                                }
                            }
                        } catch (ParseException e) {
                            nc.setIfNew("0");
                        }
                    }
                }
                PageInfo<Videos> pageInfo = new PageInfo<>(videosByCategory);
                JSONObject jsonObject = new JSONObject();
                HashMap<String, Object> childCategory = videosMapper.getVideosCategoryByCategorySerialNumber(ca);
                jsonObject.put("category", childCategory.get("videoCategory").toString());
                jsonObject.put("videos", pageInfo.getList());
                jsonObject.put("total", pageInfo.getTotal());
                if (!pageInfo.getList().isEmpty()) {
                    list.add(jsonObject);
                }
            });
        }else {
            HashMap<String, Object> videosCategory = videosMapper.getVideosCategoryByCategorySerialNumber(category);
            if (!ObjectUtils.isEmpty(videosCategory)) {
                List<String> treeList = Lists.newArrayList();
                treeList.add(videosCategory.get("videoCategorySerialNumber").toString());
                List<HashMap<String, Object>> treeListByParentSerialNumber = videosMapper.getVideosCategoryChildIdList(category);
                if (!ObjectUtils.isEmpty(treeListByParentSerialNumber)) {
                    treeListByParentSerialNumber.forEach(nc -> {
                        treeList.add(nc.get("videoCategorySerialNumber").toString());
                    });
                }
                treeList.forEach(ca -> {
                    PageHelper.startPage(pageNum, pageSize);
                    List<Videos> videosByCategory = videosMapper.getVideosByCategory(ca, search,environment);
                    for (Videos nc : videosByCategory) {
                        if (nc.getCreateDatetime() != null) {
                            try {
                                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                if (( new Date().getTime() - dateFormat.parse(nc.getCreateDatetime()).getTime())/(24*60*60*1000) <= 3) {
                                    nc.setIfNew("1");
                                }else{
                                    nc.setIfNew("0");
                                }
                            } catch (ParseException e) {
                                nc.setIfNew("0");
                            }
                            if(StringUtils.isNotEmpty(phone)) {
                                JSONObject lastRecentViewRecord = videosMapper.getLastRecentViewRecord(nc.getVideoSerialNumber(), phone);
                                if (!ObjectUtils.isEmpty(lastRecentViewRecord)) {
                                    nc.setLastRecentViewRecord(lastRecentViewRecord);
                                }
                            }
                        }
                    }
                    PageInfo<Videos> pageInfo = new PageInfo<>(videosByCategory);
                    JSONObject jsonObject = new JSONObject();
                    HashMap<String, Object> childCategory = videosMapper.getVideosCategoryByCategorySerialNumber(ca);
                    jsonObject.put("category", childCategory.get("videoCategory").toString());
                    jsonObject.put("videos", pageInfo.getList());
                    jsonObject.put("total", pageInfo.getTotal());
                    if (!pageInfo.getList().isEmpty()) {
                        list.add(jsonObject);
                    }
                });
            }
        }
        return list;

    }


    @Override
    public List<JSONObject> getVideosByTags(String tags, String search, String phone, int environment, int pageNum, int pageSize) {
        List<JSONObject> list = Lists.newArrayList();
        if(ObjectUtils.isEmpty(tags)){
            List<String> treeList = Lists.newArrayList();
            List<VideosTags> treeListByParentSerialNumber = videosMapper.getVideosTagsList("","");
            if (!ObjectUtils.isEmpty(treeListByParentSerialNumber)) {
                treeListByParentSerialNumber.forEach(nc -> {
                    treeList.add(nc.getVideoTagSerialNumber());
                });
            }
            treeList.forEach(tg -> {
                PageHelper.startPage(pageNum, pageSize);
                List<Videos> videosByCategory = videosMapper.getVideosByTags(tg,search,environment);
                for (Videos nc : videosByCategory) {
                    if (nc.getCreateDatetime() != null) {
                        try {
                            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            if (( new Date().getTime() - dateFormat.parse(nc.getCreateDatetime()).getTime())/(24*60*60*1000) <= 3) {
                                nc.setIfNew("1");
                            }else{
                                nc.setIfNew("0");
                            }
                            if(StringUtils.isNotEmpty(phone)) {
                                JSONObject lastRecentViewRecord = videosMapper.getLastRecentViewRecord(nc.getVideoSerialNumber(), phone);
                                if (!ObjectUtils.isEmpty(lastRecentViewRecord)) {
                                    nc.setLastRecentViewRecord(lastRecentViewRecord);
                                }
                            }
                        } catch (ParseException e) {
                            nc.setIfNew("0");
                        }
                    }
                }
                PageInfo<Videos> pageInfo = new PageInfo<>(videosByCategory);
                JSONObject jsonObject = new JSONObject();
                VideosTags videosTags = videosMapper.getVideosTagsByTagsSerialNumber(tg);
                jsonObject.put("tags", videosTags);
                jsonObject.put("videos", pageInfo.getList());
                jsonObject.put("total", pageInfo.getTotal());
                if (!pageInfo.getList().isEmpty()) {
                    list.add(jsonObject);
                }
            });
        }else {
            VideosTags videosTags =  videosMapper.getVideosTagsByTagsSerialNumber(tags);
            if (!ObjectUtils.isEmpty(videosTags)) {
                List<String> treeList = Lists.newArrayList();
                treeList.add(videosTags.getVideoTagSerialNumber());
                treeList.forEach(tg -> {
                    PageHelper.startPage(pageNum, pageSize);
                    List<Videos> videosByCategory = videosMapper.getVideosByTags(tg, search,environment);
                    for (Videos nc : videosByCategory) {
                        if (nc.getCreateDatetime() != null) {
                            try {
                                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                if (( new Date().getTime() - dateFormat.parse(nc.getCreateDatetime()).getTime())/(24*60*60*1000) <= 3) {
                                    nc.setIfNew("1");
                                }else{
                                    nc.setIfNew("0");
                                }
                                if(StringUtils.isNotEmpty(phone)) {
                                    JSONObject lastRecentViewRecord = videosMapper.getLastRecentViewRecord(nc.getVideoSerialNumber(), phone);
                                    if (!ObjectUtils.isEmpty(lastRecentViewRecord)) {
                                        nc.setLastRecentViewRecord(lastRecentViewRecord);
                                    }
                                }
                            } catch (ParseException e) {
                                nc.setIfNew("0");
                            }
                        }
                    }
                    PageInfo<Videos> pageInfo = new PageInfo<>(videosByCategory);
                    JSONObject jsonObject = new JSONObject();
                    VideosTags tagsVideos = videosMapper.getVideosTagsByTagsSerialNumber(tg);
                    jsonObject.put("tags", tagsVideos);
                    jsonObject.put("videos", pageInfo.getList());
                    jsonObject.put("total", pageInfo.getTotal());
                    if (!pageInfo.getList().isEmpty()) {
                        list.add(jsonObject);
                    }
                });
            }
        }
        return list;
    }

    @Override
    public JSONObject getMicroRedLookVideo(String tags, String phone,int environment, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Videos> videosByCategory = videosMapper.getMicroRedLookVideo(tags,environment);
        for (Videos nc : videosByCategory) {
            if (nc.getCreateDatetime() != null) {
                try {
                    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    if (( new Date().getTime() - dateFormat.parse(nc.getCreateDatetime()).getTime())/(24*60*60*1000) <= 3) {
                        nc.setIfNew("1");
                    }else{
                        nc.setIfNew("0");
                    }
                    if(StringUtils.isNotEmpty(phone)) {
                        JSONObject lastRecentViewRecord = videosMapper.getLastRecentViewRecord(nc.getVideoSerialNumber(), phone);
                        if (!ObjectUtils.isEmpty(lastRecentViewRecord)) {
                            nc.setLastRecentViewRecord(lastRecentViewRecord);
                        }
                    }
                } catch (ParseException e) {
                    nc.setIfNew("0");
                }
            }
        }
        PageInfo<Videos> pageInfo = new PageInfo<>(videosByCategory);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getMicroRedLookVideoTagsList() {
        List<VideosTags> themeList = videosMapper.getVideosTagsList("", "VT0000000000017");


        List<VideosTags>  bgList = videosMapper.getVideosTagsList("", "VT0000000000018");


        JSONObject jsonObject = new JSONObject();
        List<JSONObject> themeJsonList = Lists.newArrayList();

        JSONObject allTh = new JSONObject();
        allTh.put("title","全部题材");
        allTh.put("value","");
        themeJsonList.add(allTh);

        themeList.forEach(th->{
            JSONObject thJson = new JSONObject();
            thJson.put("title",th.getVideoTag());
            thJson.put("value",th.getVideoTagSerialNumber());
            themeJsonList.add(thJson);
        });
        List<JSONObject> bgJsonList = Lists.newArrayList();
        JSONObject bgJson = new JSONObject();
        bgJson.put("title","全部时代背景");
        bgJson.put("value","");
        bgJsonList.add(bgJson);

        bgList.forEach(bg->{
            JSONObject allBg = new JSONObject();
            allBg.put("title",bg.getVideoTag());
            allBg.put("value",bg.getVideoTagSerialNumber());
            bgJsonList.add(allBg);
        });
        jsonObject.put("themeList",themeJsonList);
        jsonObject.put("bgList",bgJsonList);
        return jsonObject;
    }

    @Override
    public Videos getVideosDetail(String videoSerialNumber,String phone) {
        videosMapper.addViewCount(videoSerialNumber);
        Videos videos =  videosMapper.getVideosDetail(videoSerialNumber);
        if(StringUtils.isNotEmpty(phone)) {
            JSONObject lastRecentViewRecord = videosMapper.getLastRecentViewRecord(videoSerialNumber, phone);
            if (!ObjectUtils.isEmpty(lastRecentViewRecord)) {
                videos.setLastRecentViewRecord(lastRecentViewRecord);
            }
        }
        return videos;
    }

    @Override
    public List<VideosTags> getVideosTagsList() {
        return videosMapper.getVideosTagsList("","");
    }

    @Override
    public List<VideosCategory> getVideosCategoryList() {
        List<VideosCategory> videosCategoryOneLevelList = videosMapper.getOneLevelCategory();
        List<VideosCategory> resultList = Lists.newArrayList();
        for (VideosCategory videosCategory : videosCategoryOneLevelList) {
            List<VideosCategory> allList = videosMapper
                    .selectTreeListByParentSerialNumber(videosCategory.getVideoCategorySerialNumber());
            if(CollectionUtils.isEmpty(allList)) {
                resultList.add(videosCategory);
            }else {
                allList.add(videosCategory);
                resultList.add(buildTree(allList));
            }
        }
        return resultList;
    }



    public static VideosCategory buildTree(List<VideosCategory> data) {
        Map<String, VideosCategory> nodeMap = new HashMap<>();
        VideosCategory root = null;

        // Step 1: Create all nodes and store them in a map
        for (VideosCategory row : data) {
            ;
            VideosCategory node = new VideosCategory(
                    row.getVideoCategorySerialNumber(),
                    row.getVideoCategory(),
                    row.getParentSerialNumber(),
                    row.getRowStatus(),
                    row.getOperationID(),
                    row.getOperationDatetime());
            nodeMap.put(row.getVideoCategorySerialNumber(), node);

            // Identify the root node (no parent)
            if ( row.getParentSerialNumber() == null ||  row.getParentSerialNumber().isEmpty()) {
                root = node;
            }
        }

        // Step 2: Build the tree structure by linking parent and children
        for (VideosCategory row : data) {
            String serialNumber = ObjectUtils.isEmpty(row.getVideoCategorySerialNumber()) ? "" : row.getVideoCategorySerialNumber();
            String parentSerialNumber = ObjectUtils.isEmpty(row.getParentSerialNumber()) ? "" : row.getParentSerialNumber();

            if (parentSerialNumber != null && !parentSerialNumber.isEmpty()) {
                VideosCategory childNode = nodeMap.get(serialNumber);
                VideosCategory parentNode = nodeMap.get(parentSerialNumber);
                if (parentNode != null) {
                    if (childNode != null) {
                        parentNode.addChild(childNode);
                    }
                }
            }
        }

        return root;
    }

}
